package com.example.demogateway.filters;

import com.example.demogateway.cache.CacheUtils;
import com.example.demogateway.utils.ResponseUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.MDC;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.factory.AbstractGatewayFilterFactory;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import reactor.core.publisher.Mono;

@Component
public class NoNeedLoginGateWayFilterFactory extends AbstractGatewayFilterFactory<NoNeedLoginGateWayFilterFactory.Config> {
    private static final Logger log = LoggerFactory.getLogger(NoNeedLoginGateWayFilterFactory.class);

    @Override
    public GatewayFilter apply(NoNeedLoginGateWayFilterFactory.Config config) {
        return (exchange, chain) -> {
            ServerHttpRequest request = exchange.getRequest();
            String token = null;
            String currentUser = null;
            try {
                token = request.getHeaders().getFirst(HttpHeaders.AUTHORIZATION);

                if(!StringUtils.hasLength(token)){
                    log.info("token为空，无法获取登录用户身份");
                }else {
                    currentUser = CacheUtils.getString(token);

                }

                //将token和用户身份放到header的里，方便向下传递
                String finalToken = token;
                String finalCurrentUser = currentUser;
                request = request.mutate().headers(header -> {
                    header.add(HttpHeaders.AUTHORIZATION, finalToken);
                    header.add("currentuser", finalCurrentUser);
                    header.add(AccessLogGlobalFilter.traceId, MDC.get(AccessLogGlobalFilter.traceId));
                }).build();

                return chain.filter(exchange.mutate().request(request).build());


            }finally {

            }

        };



    }

    public static class Config {
        //TODO: relaxed HttpStatus converter
        private String status;

        public String getStatus() {
            return status;
        }

        public void setStatus(String status) {
            this.status = status;
        }
    }
}
